#!/usr/bin/python3
# encoding=utf-8

import sys
import json
import socketserver
from socketserver import DatagramRequestHandler
from Wheel import Wheel
from conf import modules



class CarService(DatagramRequestHandler):
    w1 = None
    w2 = None

    #def __init__(self, request, client_address, server):
    #    super(CarService, self).__init__(request, client_address, server)

    def forward(self, speed):
        CarService.w1.forward(speed)
        CarService.w2.forward(speed)
        print("forward...")

    def backward(self, speed):
        CarService.w1.reverse(speed)
        CarService.w2.reverse(speed)
        print("backward...")

    def turn_left(self):
        speed = 0
        CarService.w1.reverse(speed)
        CarService.w2.forward(speed)
        print("turn left...")

    def turn_right(self):
        speed = 90
        CarService.w1.forward(speed)
        CarService.w2.reverse(speed)
        print("turn right...")

    def stop(self):
        CarService.w1.stop()
        CarService.w2.stop()

    def handle(self):
        request = self.rfile.read()
        #print(request)
        req_body = json.loads(request)
        #print(req_body)
        action = req_body.get("action", "stop")
        if action == "left":
            self.turn_left()
        elif action == "right":
            self.turn_right()
        elif action == "forward":
            self.forward(0)
        elif action == "backward":
            self.backward(0)
        elif action == "stop":
            self.stop()

    @classmethod
    def set_wheel(cls, w1, w2):
        CarService.w1 = Wheel(w1[0], w1[1])
        CarService.w2 = Wheel(w2[0], w2[1])

    @classmethod
    def run(cls, port):
        server = socketserver.ThreadingUDPServer(('127.0.0.1', port), CarService)
        server.serve_forever()


def main(port):
    w1 = [24, 23]
    w2 = [21, 20]
    CarService.set_wheel(w1, w2)
    CarService.run(port)


if __name__ == "__main__":
    main(int(sys.argv[1]))

